package com.spark.trouble

import android.annotation.SuppressLint
import android.database.DataSetObserver
import android.os.Build
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.spark.colliery.common.ext.gone
import com.spark.common.App
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.helper.MutableStatePagerAdapter
import com.spark.common.model.ResultModel
import com.spark.common.model.db.HTSubmitDetailModel
import com.spark.common.model.db.HTSubmitModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.RejectAlert
import com.spark.trouble.handle.ChkStdFragment
import com.spark.trouble.handle.DangerSourceFragment
import com.spark.trouble.handle.OnFragmentDeleteListener
import com.spark.trouble.handle.TroubleSpotFragment
import com.spark.trouble.model.ChkStdModel
import com.spark.trouble.model.HTInfoModel
import com.spark.trouble.model.HTInputResultModel
import kotlinx.android.synthetic.main.frag_hidden_trouble.*
import me.yokeyword.fragmentation.SupportFragment
import org.json.JSONArray
import org.json.JSONObject
import java.util.*

/**
 * 隐患/现场情况
 *
 * @info 处理流程状态
 *  1 -> 待处理
 *  2 -> 审核中/待审核
 *  3 -> 被驳回
 *  4 -> 确认中/待确认
 *  5 -> 整改中/待整改
 *  6 -> 验收中/待验收
 *  7 -> 验收驳回
 *  8 -> 待存储
 *  9 -> 已存储
 *  10 -> 已归档
 *
 */
class HTInfoFragment : BaseFragment() {
    private lateinit var dangerAdapter: DangerAdapter
    private val tabStrs: MutableList<String> = mutableListOf()
    // 提交参数model
    private val uploadModel: HTSubmitModel = HTSubmitModel()
    private val uploadBox = App.boxStore.boxFor(HTSubmitModel::class.java)

    private var reqHTSpot = 0x101
    private var reqStdChk = 0x102
    private var reqDangerSource = 0x103

    private var timer = Timer()
    private lateinit var tictoc: TimerTask

    private var taskId = ""
    private var taskType = "7"
    private var sourceType = 0
    // 是否是未分配任务 即 taskType == 7
    private var isUndispatchTask: Boolean = true

    companion object {
        /**
         * @param sourceType 0 -> 处理隐患 1 -> 待办
         */
        fun newInstance(sourceType: Int, taskId: String, taskType: String): HTInfoFragment {
            val htInfoFragment = HTInfoFragment()
            val args = Bundle()
            args.putInt("sourceType", sourceType)
            args.putString("taskId", taskId)
            args.putString("taskType", taskType)
            htInfoFragment.arguments = args
            return htInfoFragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_hidden_trouble
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            nsv.isNestedScrollingEnabled = true
        }
        arguments?.apply {
            sourceType = getInt("sourceType").apply {
                taskId = getString("taskId")
                taskType = getString("taskType")
                LogUtils.e("【taskid】$taskId 【taskType】${taskType}")
                isUndispatchTask = taskType == "7"
                tv_plus_hint.gone(!isUndispatchTask)
                iv_danger_source.gone(!isUndispatchTask)
                tabs.gone(!isUndispatchTask)
                ll_btns.gone(!isUndispatchTask)

                when (this) {
                    Const.htTypeProcess -> {
                        fetchInfo(taskId)
                        // 草稿
                        tv_draft.setOnClickListener {
                            uploadBox.put(uploadModel)
                            submitCheck(0)
                        }
                        // 提交
                        btn_submit.setOnClickListener {
                            submitCheck(1)
                        }
                    }
                    Const.htTypeAgency -> {
                        ll_btns.gone(false)
                        fetchInfo(taskId)
                        tv_draft.apply {
                            text = "驳回"
                            setOnClickListener {
                                activity?.apply {
                                    RejectAlert.Builder(this, "驳回理由", "请输入驳回理由")
                                            .affirm { d, str ->
                                                if (str.isNullOrBlank()) {
                                                    alert("请输入驳回理由")
                                                } else {
                                                    d.dismiss()
                                                    submitAgencyRejectVerify(this@HTInfoFragment.taskId, str!!)
                                                }
                                            }
                                            .cancel { d, i ->
                                                d.dismiss()
                                            }
                                            .create()
                                            .show()
                                }
                            }
                        }
                        btn_submit.apply {
                            text = "通过"
                            setOnClickListener { submitAgencyApproveVerify(this@HTInfoFragment.taskId) }
                        }
                    }
                }

            }
        }
        // 隐患位置
        rl_spot.setOnClickListener {
            parentFragment?.let { it as SupportFragment }?.startForResult(TroubleSpotFragment.newInstance(), reqHTSpot)
        }
        // 考核标准
        rl_level.setOnClickListener {
            parentFragment?.let { it as SupportFragment }?.startForResult(ChkStdFragment.newInstance(true, 0), reqStdChk)
        }
        // 危险源
        rl_danger.setOnClickListener {
            if (taskType == "7")
                parentFragment?.let { it as SupportFragment }?.startForResult(ChkStdFragment.newInstance(false, 1), reqDangerSource)
        }
        // 发现人
        tv_finder.text = Const.getUser()?.user?.name

        dangerAdapter = DangerAdapter(childFragmentManager, tabStrs).apply {
            registerDataSetObserver(object : DataSetObserver() {
                override fun onChanged() {
                    super.onChanged()
                    ll_dynamic.gone(dangerAdapter.count == 0)
                    pager.requestLayout()
                }
            })

        }

        pager.adapter = dangerAdapter
        tabs.apply {
            setupWithViewPager(pager)
            tabMode = TabLayout.MODE_SCROLLABLE
        }
    }

    /**
     * restore state
     */
    private fun restore(
            location: String,
            keyName: String,
            sourceDesc: String,
            createTime: Long,
            finderName: String,
            handleTime: Long,
            dangerDesc: String,
            actDesc: String,
            handleMan: String,
            files: MutableList<String>
    ) {
        tv_ht_spot.text = location
        tv_std.text = keyName
        tv_std_desc.text = sourceDesc
        tv_time.text = sdf("MM月dd日 mm:ss").format(createTime)
        tv_finder.text = finderName
        val htSubmitDetailModel = HTSubmitDetailModel(
                handleTime = handleTime.toString(),
                dangerDesc = dangerDesc,
                actDesc = actDesc,
                handleMan = handleMan
        )
        if (files.isEmpty()) {
            ll_dynamic.gone(true)
        } else {
            ll_dynamic.gone(false)
            files.forEach { htSubmitDetailModel.imgs.add(it) }
            tabPlus(htSubmitDetailModel)
        }
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        startTictoc()
    }

    override fun onSupportInvisible() {
        super.onSupportInvisible()
        stopTictoc()
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        val gson = Gson()
        when (requestCode) {
            reqHTSpot -> {
                if (resultCode == TroubleSpotFragment.resSpot) {
                    data?.apply {
                        val locate = getString("location")
                        tv_ht_spot.text = locate
                    }
                }
            }
            reqStdChk -> {
                if (resultCode == ChkStdFragment.resCodeStdChk) {
                    data?.apply {
                        gson.fromJson(getString("chkstd"), ChkStdModel.ResultMap::class.java)?.apply {
                            tv_std.text = this.categoryName
                            tv_std_desc.text = this.description
                            uploadModel.clauseId = this.clauseId.toString()
                            uploadModel.clauseFolder = this.keyName
                            uploadModel.clauseDesc = this.description
                        }
                    }
                }
            }
            reqDangerSource -> {
                if (resultCode == ChkStdFragment.resCodeDangerSource) {
                    data?.apply {
                        val type = object : TypeToken<MutableList<HTSubmitDetailModel>>() {}.type
                        gson.fromJson<MutableList<HTSubmitDetailModel>>(getString("chkstds"), type)?.apply {
                            uploadModel.childTask.let { it as ArrayList }.apply {
                                clear()
                                addAll(this)
                            }
                            tabPlus(this)
                        }
                    }
                }
            }
        }
    }

    /**
     * ready to tictoc
     */
    private fun startTictoc() {
        if (isUndispatchTask) {
            tictoc = object : TimerTask() {
                override fun run() {
                    val timeMillis = System.currentTimeMillis()
                    val time = sdf("MM月dd日 mm:ss").format(timeMillis)
                    activity?.apply {
                        runOnUiThread {
                            tv_time.text = time
                        }
                    }
                }
            }
            timer.schedule(tictoc, 0, 1000)
        }
    }

    /**
     * shutdown the tictoc
     */
    private fun stopTictoc() {
        if (isUndispatchTask) {
            if (!tictoc.cancel()) {
                tictoc.cancel()
            }
        }
    }

    /**
     * add tabs
     */
    private fun tabPlus(dangers: MutableList<HTSubmitDetailModel>) {
        val fragments = mutableListOf<Fragment>()
        dangers.forEachIndexed { i, model ->
            val tabSize = tabStrs.size
            tabStrs.add(tabSize, "危险源(${(tabSize + 1).toCN()})")
            val dangerSourceFragment = DangerSourceFragment.newInstance(i, model, isUndispatchTask)
            dangerSourceFragment.addDeleteListener(object : OnFragmentDeleteListener {
                override fun onDelete(position: Int) {
                    tabMinus(i)
                }
            })
            fragments.add(dangerSourceFragment)
        }
        dangerAdapter.adds(fragments)
    }

    /**
     * add single tab
     */
    private fun tabPlus(danger: HTSubmitDetailModel) {
        val tabSize = tabStrs.size
        tabStrs.add(tabSize, "危险源(${(tabSize + 1).toCN()})")
        val dangerSourceFragment = DangerSourceFragment.newInstance(0, danger, isUndispatchTask)
        dangerAdapter.add(dangerSourceFragment)
    }

    /**
     * delete the tab
     */
    private fun tabMinus(position: Int) {
        LogUtils.e("【位置】$position")
        dangerAdapter.remove(position)
    }

    /**
     * [handle] 提交检查
     * @param(state) 0: 草稿;1: 正常提交
     */
    private fun submitCheck(state: Int) {
        // 位置
        val htSpot = tv_ht_spot.text.toString().trim()
        if (htSpot.isNullOrBlank()) {
            alert("请输入隐患位置")
            // return
        }
        // 标准
        val std = tv_std.text.toString().trim()
        if (std.isNullOrBlank()) {
            alert("请确定考核标准")
            // return
        }
        // 危险源
        if (dangerAdapter.pageList.isEmpty()) {
            alert("请指明危险源")
            // return
        }

        uploadModel.apply {
            location = htSpot
            taskStatus = "$state"
            addTime = "${System.currentTimeMillis()}"
            childTask.let { it as MutableList }.apply {
                clear()
                addAll(dangerAdapter.summary())
            }

        }
        LogUtils.e("【隐患】$uploadModel")
        submit(state, uploadModel)
    }

    /**
     * [handle] 提交隐患记录
     */
    @SuppressLint("CheckResult")
    private fun submit(state: Int, submitMode: HTSubmitModel) {
        val ja = JSONArray()
        submitMode.childTask.forEach {
            val item = JSONObject()
            item.apply {
                // the params must contain
                put("sourceprocessorId", it.sourceprocessorId)
                if (!it.sourceId.isNullOrBlank())
                    put("sourceId", it.sourceId)
                if (!it.sourceFolder.isNullOrBlank())
                    put("sourceFolder", it.sourceFolder)
                if (!it.sourceDesc.isNullOrBlank())
                    put("sourceDesc", it.sourceDesc)
                if (!it.sourceMoney.isNullOrBlank())
                    put("sourceMoney", it.sourceMoney)
                if (!it.sourceScore.isNullOrBlank())
                    put("sourceScore", it.sourceScore)
                if (!it.troubleContent.isNullOrBlank())
                    put("troubleContent", it.troubleContent)
                if (!it.fields.isNullOrBlank())
                    put("fileIds", it.fields)
            }
            ja.put(item)
        }
        val jo = JSONObject()
        jo.apply {
            if (!submitMode.location.isNullOrBlank())
                put("location", submitMode.location)
            if (!submitMode.taskStatus.isNullOrBlank())
                put("taskStatus", submitMode.taskStatus)
            if (!submitMode.clauseId.isNullOrBlank())
                put("clauseId", submitMode.clauseId)
            if (!submitMode.clauseFolder.isNullOrBlank())
                put("clauseFolder", submitMode.clauseFolder)
            if (!submitMode.clauseDesc.isNullOrBlank())
                put("clauseDesc", submitMode.clauseDesc)
            if (!submitMode.addTime.isNullOrBlank())
                put("addTime", submitMode.addTime)
            if (ja.length() > 0)
                put("childTask", ja)
        }
        LogUtils.d(jo.toString())
        Http.request()
                .rxPost("${Const.base_url}${Const.act_sumit_troblue}", jo.toString().toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                            Gson().fromJson(it, HTInputResultModel::class.java)?.apply {
                                if (code == "200") {
                                    toast(if (state == 0) "保存成功" else "提交成功")
                                    activity?.finish()
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                            activity?.finish()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }

    /**
     * [待办] [handle] 待审核
     * */
    @SuppressLint("CheckResult")
    private fun fetchInfo(taskId: String) {
        val params = mutableMapOf("taskId" to taskId)
        Http.request()
                .rxPost("${Const.base_url}${Const.act_spot_info}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                            Gson().fromJson(it, HTInfoModel::class.java)?.apply {
                                if (code == "200" && resultMaps.isNotEmpty()) {
                                    resultMaps[0].apply {
                                        restore(
                                                location,
                                                keyName,
                                                sourceDesc,
                                                create_time,
                                                user_name,
                                                create_time,
                                                clauseDesc,
                                                troubleContent,
                                                processorName,
                                                troublePicinfo.map { it.uri }.toMutableList()
                                        )
                                    }
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )
    }

    /**
     * [待办] 所有任务 -> 待审核/待确认/隐患升级 -> 驳回
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyRejectVerify(taskId: String, rejectReason: String) {
        LogUtils.e("taskId ->>> $taskId")
        val params = mutableMapOf("taskId" to taskId, "refuseReason" to rejectReason)
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_alltask_submit_reject2_verify_confirm}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中...")
                        }
                )
    }

    /**
     * [待办] 待审核 -> 通过
     */
    @SuppressLint("CheckResult")
    private fun submitAgencyApproveVerify(taskId: String) {
        val params = mutableMapOf("taskId" to taskId, "approveState" to "2")
        Http.request()
                .rxPost("${Const.base_url}${Const.act_agency_spot_submit_verify}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ResultModel::class.java)?.apply {
                                if (code == "200") {
                                    success("提交成功")
                                    activity?.finish()
                                } else {
                                    error("提交失败")
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("提交中")
                        }
                )
    }
}

/**
 * <><><> [agency] restore state
 */
data class SpotHanAgencyInfoModel(
        var msg: String = "", // 成功
        var code: String = "", // 200
        var data: Any = Any(), // null
        var resultMaps: List<ResultMap> = listOf()
) {

    data class ResultMap(
            var source_processor_id: Int = 0, // 18
            var trouble_level: String = "", // 中警
            var solution_type: Int = 0, // 0
            var task_id: Int = 0, // 2327
            var process_time: Long = 0, // 1533268800000
            var trouble_content: String = "", // As
            var responsible_user_id: Int = 0, // 20
            var fatal: Boolean = false, // false
            var responsible_money: Int = 0, // 100
            var rectify_day: Int = 0, // 0
            var processor_id: Int = 0, // 18
            var responsible_leader_name: String = "", // 闫老师
            var acceptor_name: String = "", // 任建
            var process_type: Int = 0, // 1
            var solution_content: String = "", // QR
            var source_processor_name: String = "", // 张无忌
            var technician_name: String = "", // 张峰
            var departmentName: String = "", // 铜川福美煤矿
            var source_score: Int = 0, // 2
            var approver_id: Int = 0, // 21
            var approver_name: String = "", // 闫老师
            var source_money: Int = 0, // 100
            var solutionPICInfo: List<SolutionPICInfo> = listOf(),
            var main_id: Int = 0, // 2326
            var source_category: String = "", // 1
            var responsible_leader_id: Int = 0, // 21
            var technician_id: Int = 0, // 19
            var accept_reason: String = "", // we
            var responsible_user_name: String = "", // 袁建
            var acceptor_id: Int = 0, // 22
            var responsible_score: Int = 0, // 2
            var acceptionPICinfo: List<AcceptionPICinfo> = listOf(),
            var source_id: Int = 0, // 1
            var responsible_department_id: Int = 0, // 23
            var responsible_department_name: String = "", // 铜川福美煤矿
            var source_description: String = "" // 测试隐患源
    ) {

        data class AcceptionPICinfo(
                var filename: String = "", // 1533330222484.jpeg
                var uri: String = "", // /upload/1533330222484.jpeg
                var fileId: Int = 0 // 12466
        )


        data class SolutionPICInfo(
                var filename: String = "", // 1533330222485.jpeg
                var uri: String = "", // /upload/1533330222485.jpeg
                var fileId: Int = 0 // 12464
        )
    }
}


data class HTInfoModel(
        var msg: String = "", // 成功
        var code: String = "", // 200
        var data: Any = Any(), // null
        var resultMaps: List<ResultMap> = listOf()
) {

    data class ResultMap(
            var create_time: Long = 0, // 1532112766000
            var sourceDesc: String = "", // 测试隐患源
            var troubleContent: String = "", // As
            var user_name: String = "", // 张无忌
            var keyName: String = "", // 通风
            var location: String = "", // dfdfd888888888
            var processorName: String = "", // 张无忌
            var clauseDesc: String = "" // 维护好机电设备，做好安全措施
    )
}

/**
 * Danger Souce
 */
class DangerAdapter(fm: FragmentManager, private var tabs: MutableList<String>) : MutableStatePagerAdapter(fm) {
    override fun getPageTitle(position: Int): CharSequence? {
        return tabs[position]
    }

    fun summary(): List<HTSubmitDetailModel> {
        val childs = arrayListOf<HTSubmitDetailModel>()
        for (i in 0 until count) {
            val htDetail = getItem(i).let { it as DangerSourceFragment }.summary()
            childs.add(htDetail)
        }
        return childs
    }
}

